package cn.mily.org.controller;

import cn.mily.org.domain.Department;
import cn.mily.org.query.DepartmentQuery;
import cn.mily.org.service.IDepartmentService;
import cn.mily.basics.utils.JsonResult;
import cn.mily.basics.utils.PageBean;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@RestController
@RequestMapping("/dept")
public class DepartmentController {

    @Autowired
    private IDepartmentService service;

    @PutMapping/*添加*/
    public JsonResult add(@RequestBody Department department){
        try {
            if(department.getId()==null)/*判断是否拥有id  有为修改没有为添加*/
                service.add(department);
            else/*有id修改*/
                service.update(department);
            return new JsonResult();
        }catch (Exception e){
            e.printStackTrace();
            return new JsonResult("添加失败！");
        }
    }

    @PatchMapping/*批量删除*/
    public JsonResult pachDelete(@RequestBody Long[] ids){/*根据id数组批量删除*/
        try {
            service.patchDelete(ids);
            return new JsonResult();
        }catch (Exception e){
            e.printStackTrace();
            return new JsonResult("删除失败！");
        }
    }

    @PostMapping("/{strName}")/*获取部门信息和上级领导*/
    public List getParentName(@PathVariable("strName") String strName){
        if("mangerName".equals(strName)){/*判断请求最后的字符串*/
            return service.getMangerName();}/*获取上级领导信息*/
        else if(strName.split(":")[1]!=null) {
            Long id = new Long(strName.split(":")[1]);
            return service.findParentName(id);/*获取部门信息*/
        }else
            return null;
    }

    @DeleteMapping("/{id}")/*删除*/
    public JsonResult delete(@PathVariable("id") Long id){
        try {
            service.delete(id);/*根据id删除*/
            return new JsonResult();
        } catch (Exception e) {
            e.printStackTrace();
            return new JsonResult("添加失败！");
        }
    }

    @GetMapping("/{id}")/*根据id获取*/
    public Department findOne(@PathVariable("id") Long id){
        return service.findOne(id);/*查询单个，根据id查询*/
    }

    @PostMapping/*获取全部*/
    public PageBean<Department> findAll(@RequestBody DepartmentQuery query){
        return service.findAll(query);
    }
}
